
var box = document.getElementsByClassName('box')[0];

function createInput(num){
	var i;
	for(i = 0; i < num; i++){
		var pwdDiv = document.createElement('div');
		pwdDiv.className = 'pwdDiv';
		box.appendChild(pwdDiv);
		var pwd = document.createElement('input');
		pwd.type = 'password';
		pwd.className = 'pwd';
		pwd.maxLength = '1';
		pwd.readOnly = true;
		pwdDiv.appendChild(pwd);
	}
}

createInput(6);

var pwdDiv = document.getElementsByClassName('pwdDiv');
var pwd = document.getElementsByClassName('pwd');
var pwdCount = pwdDiv.length;
pwd[0].readOnly = false;
pwd[0].focus();

function op(){
	for(var i = 0; i < pwdCount; i++){
		pwd[i].onkeyup = function(e){
			if(e.keyCode >= 48 && e.keyCode <= 57){
				changeDiv();
			}else if(e.keyCode == '8'){
				backStep();
			}else if(e.keyCode == '13'){
				// 回车事件
				getPassword();
			}else{
				mui.toast('请输入数字密码！');
				this.value = '';
			}

			// if(i == pwdCount){
			// 	getPassword();
			// }
		}
	}
}

op();

function changeDiv(){
	for(var i = 0; i < pwdCount; i++){
		if(pwd[i].value.length == 1 && (i + 1) <= 5){
			pwd[i].blur();
			pwd[i + 1].focus();
			pwd[i + 1].readOnly = false;
		}
	}
}

function backStep(){
	for(var i = 0; i < pwdCount; i++){
		if(pwd[i].value.length == 0 && (i - 1) >= 0){
			pwd[i].blur();
			pwd[i - 1].focus();
			pwd[i - 1].readOnly = false;
			pwd[i - 1].value = '';
			break;
		}
	}
}

function getPassword(){
	var n = '';
	for(var i = 0; i < pwdCount; i++){
		n += pwd[i].value;
	}
	console.info(n);
	
	// 校验密码是否正确
	mui.confirm('约标密码错误，请重新输入！', '提示', ['取消', '重新输入'], function(e){
		if(e.index == 1){
			getPasswordBox();
			
			for(var i = 0; i < pwdCount; i++){
				pwd[i].value = '';
			}
		}
	});
}

function getPasswordBox(){
	var $pop = $("#overlay1");

    function modalHidden($ele) {
        $ele.removeClass("modal-in");
        $ele.one("transitionend", function() {
            $ele.css("display", "none");
            $pop.removeClass("active");
        });
    }

	$(".invest-btn").on("click", function() {
        $pop.addClass("active");
        var $modal = $("#pmodal");
        $modal.css("display", "block");
        $modal.addClass("modal-in");
        pwd[0].focus();

        $("#overlay1").on("click", function(e) {
            if (e.target.classList.contains("overlay")) {
                modalHidden($modal);
            }
        });
    });
}